import React, { useEffect, useState, useMemo } from 'react';
import groupBy from 'lodash/groupBy';
import PropTypes from 'prop-types';
import { Popover } from 'antd';
import GroupLabelPopupSection from './GroupLabelPopupSection';
import styles from './index.module.less';

/**
 * 分组显示树选项的展示框
 * @param props
 * @returns {JSX.Element}
 * @constructor
 */
const GroupLabel = props => {
    const { value, oldValue, data, renderTag, ...otherProps } = props;
    const [groupedValue, setGroupedValue] = useState();
    const isDifferenceMode = useMemo(() => oldValue !== false && JSON.stringify(value) !== JSON.stringify(oldValue), [
        oldValue,
        value
    ]);

    useEffect(() => {
        setGroupedValue(
            value?.length
                ? groupBy(
                    data.filter(item => value.indexOf(item.id) > -1),
                    'pId'
                )
                : null
        );
    }, [data, value]);

    // tag 渲染
    const tagRender = _value => {
        if (!groupedValue) {
            return null;
        }
        const currentNode = data.filter(item => item.id === _value)?.[0];
        if (!currentNode) {
            return null;
        }
        const currentParentNode = data.filter(item => item.id === currentNode.pId)?.[0];
        // 检查是不是被选中值的分组下面的第一个数据
        let isFirstItemInGroup = false;

        const groupedValueArray = Object.values(groupedValue);
        // eslint-disable-next-line no-plusplus
        for (let i = 0; i < groupedValueArray.length; i++) {
            const firstItem = groupedValueArray[i][0];
            if (firstItem?.id === _value) {
                isFirstItemInGroup = true;
                break;
            }
        }

        // render
        if (isFirstItemInGroup) {
            // 取得同级所有子节点
            const allItemInGroup = data
                .filter(item => item.pId === currentNode.pId)
                .map(item => ({
                    ...item,
                    label: item.title
                }));
            // @ts-ignore
            const checkedItemInGroup = groupedValue[currentNode.pId];
            return (
                <div key={_value} className={styles.selectionItem}>
                    <span>{currentParentNode.title}</span>
                    <span>
                        ({checkedItemInGroup.length}/{allItemInGroup.length})
                    </span>
                </div>
            );
        }
        return null;
    };

    const renderTagDisplay = renderTag ? renderTag(value) : value?.map(item => tagRender(item));

    return value?.length ? (
        <Popover
            content={
                isDifferenceMode ? (
                    <div className={styles.differencePopup}>
                        <GroupLabelPopupSection {...props} value={oldValue} title="原始内容" />
                        <GroupLabelPopupSection {...props} title="变更内容" />
                    </div>
                ) : (
                    <GroupLabelPopupSection {...props} />
                )
            }
            placement="top"
        >
            <div className={isDifferenceMode ? styles.differenceTag : null} {...otherProps}>{renderTagDisplay}</div>
        </Popover>
    ) : (
        renderTagDisplay
    );
};

GroupLabel.propTypes = {
    // 值
    value: PropTypes.array,
    // 旧值/原始值, 这个字段有值就显示原始值比较的弹出层
    // 这个组件特殊要求, Popup弹出层内容在流程中的展示要兼容展示原始值.
    oldValue: PropTypes.any,
    // 全部选项
    data: PropTypes.array.isRequired,
    // 浮窗的标题
    title: PropTypes.string.isRequired,
    renderPopupValueItem: PropTypes.func,
    renderTag: PropTypes.func
};

GroupLabel.defaultProps = {
    value: [], // id[]
    oldValue: false, // 做比较使用, 与 value 做比较
    renderPopupValueItem: null,
    renderTag: null
};

export default GroupLabel;
